package com.tianhao.luo.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 模拟读写锁中的缺点
 *
 * 读锁会阻塞死锁
 *
 * @author tianhao.luo@hand-china.com
 */
public class ReadWriteLockDemo2 {
    public static void main(String[] args) {
        ReadWriteLockDemo.MyCache myCache = new ReadWriteLockDemo.MyCache();

        // 1.模拟多线程读数据
        for (int i = 0; i < 3; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.get(num + " ");
            }, "线程" + num).start();
        }

        // 模拟读读
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 1.模拟多线程放数据
        for (int i = 0; i < 3; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.put(num + " ", num + " ");
            }, "线程" + num).start();
        }
    }

    // 1.创建资源类
    static class MyCache {
        private final ReadWriteLock lock = new ReentrantReadWriteLock();
        private volatile Map<String, Object> map = new HashMap<>();

        {
            map.put("1","aaa");
            map.put("2","aaa");
            map.put("3","aaa");
            map.put("4","aaa");
            map.put("5","aaa");
        }

        //放数据
        public void put(String key, Object value) {
            Lock writeLock = this.lock.writeLock();
            writeLock.lock();

            try {
                System.out.println(Thread.currentThread().getName() + " 正在写操作:" + key);

                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                map.put(key, value);
                System.out.println(Thread.currentThread().getName() + " 写完了:" + key);
            } finally {
                writeLock.unlock();
            }
        }

        //取数据
        public Object get(String key) {
            Lock readLock = this.lock.readLock();
            readLock.lock();

            try {
                System.out.println(Thread.currentThread().getName() + " 正在读操作:" + key);

                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                Object o = map.get(key);
                System.out.println(Thread.currentThread().getName() + " 读操作完成:" + key);
                return o;
            } finally {
                readLock.unlock();
            }
        }
    }
}
